package generator

import (
	"crypto/sha256"
	"encoding/hex"
	"github.com/google/uuid"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

const (
	alphabet       = "abcdefghijklmnopqrstuvwxyz"
	macAddrCharSet = "a1b2c3d4e5f6789"
)

func init() {
	rand.Seed(time.Now().UnixNano())

}

func CalculateSHA256(message string) string {
	sha256Hash := sha256.New()
	sha256Hash.Write([]byte(message))
	hashValue := sha256Hash.Sum(nil)
	hashString := hex.EncodeToString(hashValue)

	return hashString
}

func GenUidUUID() string {
	return "userid_" + uuid.New().String()
}

func GenUeUUID() string {
	return "ue_" + uuid.New().String()
}

func GenCtidUUID() string {
	return "ctid_" + uuid.New().String()
}

// GenerateHid 根据mac、uid和随机数r生成一个匿名id
func GenerateHid(mac string, uid string, r int) string {
	result := CalculateSHA256(mac+strconv.Itoa(r)) + CalculateSHA256(uid+strconv.Itoa(r))
	return result
}

// GenerateCtid 根据uid生成一个孪生id
func GenerateCtid(uid string) string {
	result := "Cybertwin_" + uid
	return result
}

func RandomInt(min, max int) int {
	return min + rand.Intn(max-min+1)
}

func GenerateRandomHid() string {
	return "hid_" + uuid.New().String()
}

func RandomString(n int) string {
	var sb strings.Builder
	k := len(alphabet)
	for i := 0; i < n; i++ {
		c := alphabet[rand.Intn(k)]
		sb.WriteByte(c)
	}
	return sb.String()
}

func GenRandomMacAddr() string {
	builder := strings.Builder{}
	// b0:be:83:5e:63:ae
	for i := 0; i < 6; i++ {
		builder.WriteByte(macAddrCharSet[RandomInt(0, len(macAddrCharSet)-1)])
		builder.WriteByte(macAddrCharSet[RandomInt(0, len(macAddrCharSet)-1)])
		builder.WriteByte(':')
	}
	s := builder.String()
	s, _ = strings.CutSuffix(s, ":")
	return s
}
